<template>
    <div class="box">
        <div class="warning">
            <el-icon size="17" color="#FF7D34">
                <Warning />
            </el-icon>
            <div class="text">可直接拖动文本进行自定义排序</div>
        </div>
        <div class="items">
            <div v-for="(item, index) in items" :key="item.id" class="item" :style="{ order: item.order }" :draggable="true"
                @dragstart="onDragStart(index)" @dragover.prevent="onDragOver" @drop="onDrop(index, $event)">
                <el-checkbox v-model="item.check" :label="item.name" size="large" />
            </div>
        </div>
    </div>
</template>
  
<script setup>
import { ref } from "vue";

const props = defineProps({
    items: {
        type: Array,
        default: () => [],
    }
})

const items = ref(props.items.map((item, index) => {
    return {
        check: item.check = true,
        order: index + 1,
        name: item.label
    }
}))
let draggedIndex = null;

//点击开始
const onDragStart = (index) => {
    // console.log(index);
    draggedIndex = index;
};

//移动触发
const onDragOver = (event) => {
    event.preventDefault();
};

//放置触发
const onDrop = (targetIndex, event) => {
    event.preventDefault();
    if (draggedIndex !== targetIndex) {
        const draggedOrder = items.value[draggedIndex].order;
        const targetOrder = items.value[targetIndex].order;
        items.value[draggedIndex].order = targetOrder;
        items.value[targetIndex].order = draggedOrder;
        //改变items的排序
        items.value.sort((a, b) => a.order - b.order);
    }
    console.log(items.value)
};

defineExpose({ // 暴露 items 给父组件
    getItems: () => items.value
});
</script>
  
<style lang="scss" scope>
.box {
    display: flex;
    flex-wrap: wrap;
}

.warning {
    display: flex;
    /* justify-content: center; */
    align-items: center;
    width: 100%;
    height: 54px;
    border-radius: 6px;
    background: #FF7D3423;
    border: 1px solid #FF7D34;
    margin-bottom: 24px;
    padding: 16px 24px;

    .text {
        margin-left: 10px;
    }
}

.items {
    display: flex;
    justify-content: start;
    align-items: center;
    width: 100%;
    flex-wrap: wrap;

    .item {
        width: calc(20% - 8px);
        margin-right: 8px;
        padding: 8px;
    }
}

:deep(.el-checkbox__input) {
    color: #000000 !important;
}





/* 
.item {
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    background-color: #f3f3f3;
    margin: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    cursor: move;
    user-select: none;
    transition: background-color 0.3s;
}

.item:active {
    background-color: #ddd;
} */
</style>
  
  